﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DICE_GS;
using System.Text;

public class MyUnitCard : MonoBehaviour {
	public UITexture unitImage;
	public UITexture cardElementFrame;
    public UITexture cardGradeFrame;
    public UISprite[] attributeImage;
	public UILabel[] cardName;
	public UILabel[] cardCost;
	public UILabel[] cardLevel;
	public UILabel[] cardDefense;
	public UILabel[] cardAttack;
	public UILabel[] cardMove;
	public UILabel[] cardSkillName;
	public UILabel cardSkillDesc;
	public GameObject[] cardStars;
	public UILabel statsLabel;
	
	public GameObject slot;
	public GameObject blankSlot;

    public GameObject alreadySettingLabel;

    public GameObject CursorCard;
	
	[HideInInspector]
	public WaitingRoomSceneManager sceneManager;
	[HideInInspector]
	public DeckEditSceneManager editSceneManager;
	[HideInInspector]
	public MyUnitListManager unitListManager;
	
	[HideInInspector]
	public int index;

    [HideInInspector]
    public bool isSelectUnitMode = false;
	
	Transform trans = null;
	Vector3 prevPosition;
	
	//public bool disableOnPress;
	
	public UILabel hpLabel;
	public GameObject selectedMark;
	
	public GameObject selectButtonObject;
	public GameObject takeOffButtonObject;
	
	public GameObject equipInfoObject;
	public GameObject equipLimitObject;

    public GameObject Btn_Close;
    public GameObject Check;
	// Use this for initialization
	void Start () {
		prevPosition = transform.localPosition;       
        m_Panel = GetComponent<UIPanel>();

        m_OririnPos = transform.localPosition;
        m_OrizinScale = transform.localScale;
	}

	
	public UnitInfo _unitInfo;
	public void SetCardInfo(int index, UnitInfo unitInfo)
	{
        _unitInfo = unitInfo;
		this.index = index;

        if (_unitInfo == null)
            return;

		prevPosition = transform.localPosition;		

		CUnitData unitData = CUnitDataManager.Instance.GetUnitData(unitInfo.UnitClassID);
        if (unitData == null) return;

		string[] splitSkillString = new string[0];
		if( !string.IsNullOrEmpty(unitData.passive_skill) )
			splitSkillString = unitData.passive_skill.Split(';');
		
		cardName[0].text = unitInfo.name;

        if (splitSkillString.Length != 0 && cardSkillName.Length > 0)
        {
            cardSkillName[0].text = CStringTableManager.Instance.GetItemByName(CSkillDataManager.Instance.FindSkillData(splitSkillString[0]).name_string);
            cardSkillName[0].gameObject.SetActive(true);
        }
		cardLevel[0].text = unitInfo.UnitLevel.ToString();
        if (cardDefense.Length > 0)
            cardDefense[0].text = unitInfo.defense.ToString();
        if (cardAttack.Length > 0)
            cardAttack[0].text = unitInfo.attack.ToString();
        if (cardMove.Length > 0)
            cardMove[0].text = unitInfo.move.ToString();
        if (cardCost.Length > 0)
            cardCost[0].text = unitInfo.cost.ToString();
        //if( unitInfo.element == element.sky )
        //    attributeImage[0].spriteName = 

        StringBuilder builder = new StringBuilder();
		builder.Append(CStringTableManager.Instance.GetItemById(1315));
		builder.Append(unitInfo.attack);
		builder.Append(" ");
		builder.Append(CStringTableManager.Instance.GetItemById(1319));
		builder.Append(unitInfo.defense);
		builder.Append(" ");
		builder.Append(CStringTableManager.Instance.GetItemById(1323));
		builder.Append(unitInfo.move);
		if( statsLabel != null)
			statsLabel.text = builder.ToString();
		if( hpLabel != null )
			hpLabel.text = unitInfo.hp.ToString();
		
//		unitImage.spriteName = unitData.name;
		Texture2D tex = Resources.Load(unitData.name) as Texture2D;
		if( tex != null )
			unitImage.mainTexture = tex;
		else
			unitImage.mainTexture = Resources.Load("N_ea_01") as Texture2D;
//		if( unitImage.GetAtlasSprite() == null )
//			unitImage.spriteName = "N_ea_01";
        
        if (cardElementFrame != null)
        {
            tex = Resources.Load("Card_frame_" + unitData.element) as Texture2D;
            if (tex != null)
                cardElementFrame.mainTexture = tex;
            else
                cardElementFrame.mainTexture = Resources.Load("Card_frame_earth") as Texture2D;
        }

        if (cardGradeFrame != null)
        {
            if (unitData.evolution_step == 1)
                cardGradeFrame.gameObject.SetActive(false);
            else if (unitData.evolution_step == 2)
            {
                tex = Resources.Load("Card_frame_Silver") as Texture2D;
                if (tex != null)
                {
                    cardGradeFrame.mainTexture = tex;
                    cardGradeFrame.gameObject.SetActive(true);
                }
                else
                    cardGradeFrame.gameObject.SetActive(false);
            }
            else if (unitData.evolution_step == 3)
            {
                tex = Resources.Load("Card_frame_Gold") as Texture2D;
                if (tex != null)
                {
					cardGradeFrame.mainTexture = tex;
                    cardGradeFrame.gameObject.SetActive(true);
                }
                else
					cardGradeFrame.gameObject.SetActive(false);
            }
        }

		attributeImage[0].spriteName = "card_symbol_" + unitData.element;
		
		foreach(GameObject sprite in cardStars)
			sprite.gameObject.SetActive(false);
		
		for(int i=0; i<unitData.grade; i++)
		{
			cardStars[i].gameObject.SetActive(true);
		}

        if (splitSkillString.Length != 0 && cardSkillDesc != null)
        {
            cardSkillDesc.text = CStringTableManager.Instance.GetItemByName(CSkillDataManager.Instance.FindSkillData(splitSkillString[0]).desc_string);
            cardSkillDesc.gameObject.SetActive(true);
        }
	}

    public void SetCardInfo(int index, int unitLevel, CUnitData unitData, CUnitAbilityItem plusData)
    {
        this.index = index;
        prevPosition = transform.localPosition;

        string[] splitSkillString = new string[0];
        if (!string.IsNullOrEmpty(unitData.passive_skill))
            splitSkillString = unitData.passive_skill.Split(';');

        cardName[0].text = CStringTableManager.Instance.GetItemByName(unitData.name_string);

        if (splitSkillString.Length != 0 && cardSkillName.Length > 0)
        {
            cardSkillName[0].text = CStringTableManager.Instance.GetItemByName(CSkillDataManager.Instance.FindSkillData(splitSkillString[0]).name_string);
            cardSkillName[0].gameObject.SetActive(true);
        }
        cardLevel[0].text = unitLevel.ToString();
		CUnitAbilityItem plusData_LV1 = CUnitAbilityDataManager.Instance.GetUnitAbilityData("1_" + unitData.unit_class);
        if (cardDefense.Length > 0)
            cardDefense[0].text = (unitData.defense_base + plusData_LV1.defense + plusData.defense).ToString();
        if (cardAttack.Length > 0)
			cardAttack[0].text = (unitData.attack_base + plusData_LV1.attack + plusData.attack).ToString();
        if (cardMove.Length > 0)
			cardMove[0].text = (unitData.move_base + plusData_LV1.move + plusData.move).ToString();
        if (cardCost.Length > 0)
            cardCost[0].text = unitData.unit_cost.ToString();

        StringBuilder builder = new StringBuilder();
        builder.Append(CStringTableManager.Instance.GetItemById(1315));
        builder.Append((unitData.attack_base + plusData.attack).ToString());
        builder.Append(" ");
        builder.Append(CStringTableManager.Instance.GetItemById(1319));
        builder.Append((unitData.defense_base + plusData.defense).ToString());
        builder.Append(" ");
        builder.Append(CStringTableManager.Instance.GetItemById(1323));
        builder.Append((unitData.move_base + plusData.move).ToString());
        if (statsLabel != null)
            statsLabel.text = builder.ToString();
        if (hpLabel != null)
			hpLabel.text = (unitData.max_hp + plusData_LV1.max_hp + plusData.max_hp).ToString();

        //		unitImage.spriteName = unitData.name;
        //		if( unitImage.GetAtlasSprite() == null )
        //			unitImage.spriteName = "N_ea_01";
        Texture2D tex = Resources.Load(unitData.name) as Texture2D;
        if (tex != null)
            unitImage.mainTexture = tex;
        else
            unitImage.mainTexture = Resources.Load("N_ea_01") as Texture2D;

        if (cardElementFrame != null)
        {
            tex = Resources.Load("Card_frame_" + unitData.element) as Texture2D;
            if (tex != null)
                cardElementFrame.mainTexture = tex;
            else
                cardElementFrame.mainTexture = Resources.Load("Card_frame_earth") as Texture2D;
        }

        if (cardGradeFrame != null)
        {
            if (unitData.evolution_step == 1)
                cardGradeFrame.gameObject.SetActive(false);
            else if (unitData.evolution_step == 2)
            {
                tex = Resources.Load("Card_frame_Silver") as Texture2D;
                if (tex != null)
                {
                    cardGradeFrame.mainTexture = tex;
                    cardGradeFrame.gameObject.SetActive(true);
                }
                else
                    cardGradeFrame.gameObject.SetActive(false);
            }
            else if (unitData.evolution_step == 3)
            {
                tex = Resources.Load("Card_frame_Gold") as Texture2D;
                if (tex != null)
                {
                    cardGradeFrame.mainTexture = tex;
                    cardGradeFrame.gameObject.SetActive(true);
                }
                else
                    cardGradeFrame.gameObject.SetActive(false);
            }
        }

        attributeImage[0].spriteName = "card_symbol_" + unitData.element;

        foreach (GameObject sprite in cardStars)
            sprite.gameObject.SetActive(false);

        for (int i = 0; i < unitData.grade; i++)
        {
            cardStars[i].gameObject.SetActive(true);
        }

        if (splitSkillString.Length != 0 && cardSkillDesc != null)
        {
            cardSkillDesc.text = CStringTableManager.Instance.GetItemByName(CSkillDataManager.Instance.FindSkillData(splitSkillString[0]).desc_string);
            cardSkillDesc.gameObject.SetActive(true);
        }
    }


    public UnitInfo GetCardInfo()
    {
        return _unitInfo;
    }

  
	public void CreateDummyCard()
	{
		if( trans == null )
		{
			MonoBehaviour card = LTPrefabManager.InstantiateC(PrefabTypes.Card, prevPosition, Quaternion.identity) as MonoBehaviour;
			trans = card.transform;
			trans.parent = transform.parent;
			trans.localPosition = transform.localPosition;
			trans.GetComponent<UIPanel>().depth = -10-index;
			trans.localScale = Vector3.one;
			MyUnitCard cardScript = card.GetComponent<MyUnitCard>();
			cardScript.slot.SetActive(true);
			cardScript.blankSlot.SetActive(false);
			cardScript.SetCardInfo(this.index, _unitInfo);
			cardScript.sceneManager = sceneManager;
			//cardScript.disableOnPress = true; 
		}
	}
	
	public void HideDummyCard()
	{
		if( trans != null )
		{
			trans.gameObject.SetActive(false);
			trans.localPosition = prevPosition;
		}
	}
	
    //public void OnPressFromDummy(bool pressed)
    //{
    //    Debug.Log("OnPressFromDummy");
    //    //OnPress(pressed);
    //}
	
//    void OnPress (bool pressed)
//    {
//        if(disableOnPress)
//            return;
//        /*
//        if( CSceneManager.m_Scene == SCENE.MainScene )
//        {					
//            if( pressed )
//            {
//                if( !blankSlot.activeSelf && trans != null )
//                {
//                    trans.GetComponent<UIPanel>().depth = 20+index;
//                    trans.gameObject.SetActive(true);
//                    TweenScale tweenScaleStart = TweenScale.Begin(trans.gameObject, 0.3f, new Vector3(2.9f,2.9f,1f));
//                    TweenPosition tweenPositionStart = TweenPosition.Begin(trans.gameObject, 0.3f, new Vector3(-945f,-360f, -10f));
//                    TweenAlpha tweenAlpha2 = TweenAlpha.Begin(trans.gameObject, 0.3f, 1.0f);
//                    TweenAlpha tweenAlpha = TweenAlpha.Begin(gameObject, 0.3f, 0.5f);
//                }
//            }
//            else
//            {
//                if( !blankSlot.activeSelf && trans != null  )
//                {
//                    TweenScale tweenScaleEnd = TweenScale.Begin(trans.gameObject, 0.3f, Vector3.one);
//                    TweenPosition tweenPositionEnd = TweenPosition.Begin(trans.gameObject, 0.3f, prevPosition);
//                    TweenAlpha tweenAlpha2 = TweenAlpha.Begin(trans.gameObject, 0.3f, 0.5f);
//                    TweenAlpha tweenAlpha = TweenAlpha.Begin(gameObject, 0.3f, 1.0f);
//                    EventDelegate.Add(tweenPositionEnd.onFinished, tweenPositionCallback, true); 
//                }
				
//                if( sceneManager.isDragging )
//                    sceneManager.isDragging = false;
//            }
////			transform.parent.parent.parent.GetComponent<UIDraggablePanel>().Press(pressed);
//        }
//        */
//    }
	
	
				
	void tweenPositionCallback()
	{
		trans.gameObject.SetActive(false);
		trans.GetComponent<UIPanel>().depth = -10-index;
	}


    public void ClickedUnitCard()
    {
        if (CSceneManager.m_Scene == SCENE.UnitInvenScene)
        {
        }
        else if (CSceneManager.m_Scene == SCENE.DeckEditScene)
        {
            editSceneManager.ClickedTeamCard();
            //editSceneManager.DeActiveCardSelectButtons(index);
            //selectButtonObject.SetActive(!selectButtonObject.activeSelf);
            //takeOffButtonObject.SetActive(!takeOffButtonObject.activeSelf);
        }
    }

    
	void OnClickedSelectButton()
	{
		LoadingWindow.window.ShowShortLoading();
		CSceneManager.manager.GoToUnitInvenScene();
	}


    //카드교체 관련 변수

    const float CardPickupDelay = 0.5f;
    float m_PickupTimer = 0;
    bool m_IsPressing = false;
    bool m_IsPickup = false; // 카드 손에 쥐고 있는지
    Camera cam;
    UIPanel m_Panel;
    Vector3 m_OririnPos;
    Vector3 m_OrizinScale;

    void OnPress(bool isPress)
    {
        if(CSceneManager.m_Scene != SCENE.DeckEditScene )
			return;

        if (!isSelectUnitMode)
        {
            m_IsPressing = isPress;

            if (!isPress)
            {
                if (m_Panel != null)
                    m_Panel.depth = 2;
                m_PickupTimer = 0;
                m_IsPickup = false;

                RaycastHit hit;
                Ray ray = cam.ScreenPointToRay(Input.mousePosition);

                if (Physics.Raycast(ray, out hit))
                {
                    if (hit.collider.name.Contains("Card"))
                    {
                        MyUnitCard tempCard = hit.collider.GetComponent<MyUnitCard>();

                        if (tempCard == null) //블랭크 카드
                        {
                            string indexString = hit.collider.name.Replace("BlankCard", "");
                            tempCard = transform.parent.FindChild(string.Format("Card{0}", indexString)).GetComponent<MyUnitCard>();

                            hit.collider.gameObject.SetActive(false);
                            transform.parent.FindChild(string.Format("BlankCard{0}", index + 1)).gameObject.SetActive(true);

                            tempCard.gameObject.SetActive(true);
                            gameObject.SetActive(false);

                            tempCard._unitInfo = new UnitInfo(0, 0);
                        }

                        UnitInfo tempInfo = _unitInfo;

                        SetCardInfo(index, tempCard.GetCardInfo());
                        MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].SlotMap[index] = tempCard.GetCardInfo();
                        tempCard.SetCardInfo(tempCard.index, tempInfo);
                        MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].SlotMap[tempCard.index] = tempInfo;
                    }
                }

                transform.localScale = m_OrizinScale;
                transform.localPosition = m_OririnPos;
                collider.enabled = true;
            }
            else
                cam = GameObject.Find("UI Root (2D)/Camera").camera;
        }
    }  
      

    void OnDrag(Vector2 delta)
    {
        if (!isSelectUnitMode)
        {
            //Vector2 pos2 = Input.mousePosition;

            Vector3 pos = Vector3.zero;
		    if( cam != null )
        	    pos = cam.ScreenToWorldPoint(Input.mousePosition);

            if (m_IsPickup)
            {
                Vector3 tPos = gameObject.transform.position;
                tPos.x = pos.x;
                tPos.y = pos.y;
                gameObject.transform.position = tPos;
            }
        }
        else
        {
            unitListManager.Drag(delta);
        }

		if( unitListManager != null )
			unitListManager.Drag(delta);
    }

    void Update()
    {
		if(CSceneManager.IsIngameScene())
			return;

        if (CSceneManager.m_Scene == SCENE.DeckEditScene)
        {
            if (!isSelectUnitMode)
            {
                if (m_IsPressing && !m_IsPickup)
                {
                    m_PickupTimer += Time.deltaTime;
                    if (m_PickupTimer > CardPickupDelay)
                    {
                        m_IsPickup = true;
                        m_PickupTimer = 0;

                        transform.localScale = m_OrizinScale * 0.8F;
                        m_Panel.depth = 5;

                        collider.enabled = false;
                    }
                }
            }
        }       
    }

    public void SetCheck(bool isCheck)
    {
        _unitInfo.isChecked = isCheck;
        Check.SetActive(isCheck);
    }

    public bool IsCheck()
    {
        return Check.activeSelf;
    }
}
